package com.wn.netty.sample;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @FileName: QucikStart
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/7/28 - 16:15
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class QuickStartServer {

    private static final int CORE_THREAD_COUNT = Runtime.getRuntime().availableProcessors();


    public static void main(String[] args) {
        // 创建事件循环组
        EventLoopGroup bossGroup = new NioEventLoopGroup(CORE_THREAD_COUNT);
        EventLoopGroup workerGroup = new NioEventLoopGroup(CORE_THREAD_COUNT);

        try {
            // 创建启动器
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    // 设置服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列得到连接个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置连接保持活动状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new MyServerChannelHandler());
                        }
                    });

            System.out.println("服务器已准备好...");
            // 启动,绑定端口,设置同步
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            // 给future设置监听
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("绑定端口成功");
                    return;
                }
                System.out.println("绑定端口失败");
            });
            // 设置监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
